import heapq
class Solution(object):
    def eatenApples(self, apples, days):
        n = len(apples)
        st = []
        ans = 0
        for i in range(n):
            if apples[i]:
                heapq.heappush(st, [i + days[i] - 1, apples[i]])
            while st and st[0][0] < i:
                heapq.heappop(st)
            if st:
                x, y = heapq.heappop(st)
                ans += 1
                y -= 1
                if y > 0 and x > i:
                    heapq.heappush(st, [x, y])
        index = n
        while st:
            while st and st[0][0] < index:
                heapq.heappop(st)
            if st:
                x, y = heapq.heappop(st)
                ans += min(x - index + 1, y)
                index += min(x - index + 1, y)
        return ans
